﻿using System;
using System.Collections.Generic;

using System.Text;
using Microsoft.Win32;

namespace AutoUpdate
{
    class RegOperation
    {
        
        /// <summary>
        /// 检查注册表中是否已经存在PowerSysClient项和ServiceIP键，如果没有，创建
        /// </summary>
        public static void RegedieAdd(string vaule,string keyname)
        {
            if (!IsRegeditItemExist())//首先判断是否存在PowerSysClient项，没有就建立
            {
                RegistryKey key = Registry.LocalMachine;//获取HKEY_LOCAL_MACHINE节点
                key.CreateSubKey("software\\PowerSysClient");//建立该节点，如果该节点已经存在，则不影响
            }
            if (!IsRegeditKeyExit(keyname))//然后判断PowerSysClient项中是否有ServiceIP键，没有就添加记录
            {
                RegistryKey key = Registry.LocalMachine;
                RegistryKey software = key.OpenSubKey("software\\PowerSysClient", true);  //该项必须已存在
                software.SetValue(keyname, vaule);
            }
        }

        /// <summary>
        /// 判断是否存在PowerSysClient节点
        /// </summary>
        /// <returns></returns>
        public static bool IsRegeditItemExist()
        {
            string[] subkeyNames;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE");
            //RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);  
            subkeyNames = software.GetSubKeyNames();
            //取得该项下所有子项的名称的序列，并传递给预定的数组中  
            foreach (string keyName in subkeyNames)   //遍历整个数组  
            {
                if (keyName == "PowerSysClient") //判断子项的名称  
                {
                    hkml.Close();
                    return true;
                }
            }
            hkml.Close();
            return false;
        }

        /// <summary>
        /// 判断密码是否存在（判断是否存在ServiceIP键）
        /// </summary>
        /// <returns></returns>
        public static bool IsRegeditKeyExit(string parkeyname)
        {
            string[] subkeyNames;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE\\PowerSysClient");
            subkeyNames = software.GetValueNames();
            //取得该项下所有键值的名称的序列，并传递给预定的数组中   
            foreach (string keyName in subkeyNames)
            {
                if (keyName == parkeyname)    //判断键值的名称   
                {
                    hkml.Close();
                    return true;
                }
            }
            hkml.Close();
            return false;
        }
    }
}
